//
//  PersonInfoController.m
//  History
//
//  Created by 七 on 16/9/10.
//  Copyright © 2016年 kane. All rights reserved.
//

#import "PersonInfoController.h"
#import "EditNickNameController.h"


@interface PersonInfoController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITableViewDelegate,UITableViewDataSource>
{
    __weak IBOutlet UIView *navView;
    IBOutlet UIView *BGView;
    __weak IBOutlet UITableView *profileTable;
    __weak IBOutlet UILabel *lineLbl;
    UIButton *headImgBtn;
    NSMutableArray *selectedAssets;
    NSMutableArray *selectedPhotos;
    NSInteger type;
    UILabel *nickNameLbl;
}
@end

@implementation PersonInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [nickNameLbl removeFromSuperview];
    [profileTable reloadData];
}

#pragma mark - User Action
- (IBAction)backBtnPress:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UITableView Delegate && Datasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 80;
    }else{
        return 40;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identify = [NSString stringWithFormat:@"%ld%ld",(long)indexPath.section,(long)indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
    }
    cell.backgroundColor = KKColor_DarkGray_White;
    cell.textLabel.textColor = KKColor_Black_LightGary;
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    if (indexPath.row == 0) {
        cell.textLabel.text = @"头像";
        headImgBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-100, 10, 60, 60)];
        [headImgBtn setImageForState:UIControlStateNormal withURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",FileURL,[UserEntity sharedUser].PictureUrl]]];
        headImgBtn.layer.cornerRadius = headImgBtn.frame.size.width/2.0;
        headImgBtn.layer.masksToBounds = headImgBtn.frame.size.width/2.0;
        [cell addSubview:headImgBtn];
    }else{
        cell.textLabel.text = @"昵称";
        nickNameLbl = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width-140, 0, 100, 40)];
        nickNameLbl.font = [UIFont systemFontOfSize:12];
        nickNameLbl.textColor = [UIColor darkGrayColor];
        nickNameLbl.textAlignment = NSTextAlignmentRight;
        nickNameLbl.text = [UserEntity sharedUser].NickName;
        [cell addSubview:nickNameLbl];
    }
    return cell;
}


-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照" ,@"从手机相册选择", nil];
        sheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
        [sheet showInView:self.view];
    }else{
        EditNickNameController *editVC = [[EditNickNameController alloc] init];
        [self.navigationController pushViewController:editVC animated:YES];
    }
}

#pragma mark - UIActionSheet Delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        switch (buttonIndex) {
            case 0:
                // 相机
                sourceType = UIImagePickerControllerSourceTypeCamera;
                break;
            case 1:
                // 相册
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
            default:
                break;
        }
    } else {
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    if (buttonIndex!=2) {
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = sourceType;
        [self presentViewController:imagePickerController animated:YES completion:^{}];
    }
}




#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSData *imageData = UIImageJPEGRepresentation([self imageScaled:image],1);
    NSString *fileName = [NSString stringWithFormat:@"%lld.jpg",(long long)[[NSDate date] timeIntervalSince1970]];
    [WebService saveUploadFile:imageData
                      fileName:fileName
                    WithParams:@{}
                    uploadPath:@"uploadAvatar"
                     WithBlock:^(id result, NSError *error) {
                         if (!error) {
                             if ([result[@"code"] integerValue] == 0) {
                                 NSArray *ary = result[@"value"];
                                 if (ary.count > 0) {
                                     NSDictionary *dic = ary.firstObject;
                                     [self commitAvatar:[dic[@"path"] convertToString]];
                                 }
                             }
                         }
                     }];
}

- (void)commitAvatar:(NSString *)path
{
    NSDictionary *params  = @{@"c_id":[[UserEntity sharedUser] getUserID],@"c_photo":path};
//    WebService upda
    [UserEntity sharedUser].PictureUrl = path;
    [headImgBtn setImageForState:UIControlStateNormal withURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",FileURL,[UserEntity sharedUser].PictureUrl]]];
}

- (UIImage *)imageScaled:(UIImage *)img
{
    UIImage *image = img;
    CGSize imagesize = image.size;
    CGFloat newWidth = 320;
    if (imagesize.width <= newWidth) {
        return image;
    }
    CGFloat newHeight = imagesize.height / imagesize.width * newWidth;
    UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight));
    [image drawInRect:CGRectMake(0,0,newWidth,newHeight)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}




@end
